package 面试2025.字节跳动;



public class K一个一组反转链表变种 {
    /**
     * 计算器说了思路,可以换题,换为这个；最终测试用例通过
     */
    public static void main(String[] args) {
        ListNode dummy = new ListNode(101);
        ListNode temp = dummy;
        for(int i = 0;i < 8;i++){
            temp.next = new ListNode(i + 1);
            temp = temp.next;
            System.out.print(temp.val + "->");
        }
        System.out.println();
        ListNode root = reverseKGroup(dummy.next, 3);
        while(root != null){
            System.out.print(root.val + "->");
            root = root.next;
        }
    }
    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(501);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode end = head;
        while(end != null){
            ListNode start = prev.next;
            for(int i = 0;i < k - 1 && end != null;i++){
                end = end.next;
            }
            if(end == null){
                prev.next = reverse(start);
                break;
            }
            ListNode next = end.next;
            end.next = null;
            prev.next = reverse(start);
            start.next = next;
            prev = start;
            end = next;
        }
        return dummy.next;
    }
    private static ListNode reverse(ListNode head){
        ListNode prev = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }

    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int val){
            this.val = val;
            next = null;
        }
    }
}
